package leetcode7;

public class test31 {
    /**
     * 148. 排序链表
     * @param head
     * @return
     */
    //暴力解法
    public ListNode sortList(ListNode head) {
        if (head == null) return null;

        Map<Integer, List<ListNode>> map = new TreeMap<>();
        ListNode cur = head;

        while (cur != null) {
            map.computeIfAbsent(cur.val, k -> new ArrayList<>()).add(new ListNode(cur.val));
            cur = cur.next;
        }

        ListNode dump = new ListNode(0);
        cur = dump;

        for (List<ListNode> nodeList : map.values()) {
            for (ListNode node : nodeList) {
                cur.next = node;
                cur = node;
            }
        }

        cur.next = null; // Make sure to end the list
        return dump.next;
    }
    //归并递归排序
    public ListNode sortList(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode fast = head.next;
        ListNode slow = head;
        while (fast != null && fast.next != null){
            slow=slow.next;
            fast=fast.next.next;
        }
        ListNode temp = slow.next;
        slow.next = null;
        ListNode left = sortList(head);
        ListNode right = sortList(temp);
        ListNode dump = new ListNode(0);
        ListNode cur = dump;
        while(left != null || right != null){
            if(left == null){
                cur.next = right;
                break;
            }
            if(right == null){
                cur.next = left;
                break;
            }
            if(left.val < right.val){
                cur.next = left;
                left = left.next;

            }else{
                cur.next = right;
                right = right.next;

            }
            cur = cur.next;
        }
        return  dump.next;
    }
}
